from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 定义User模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)

    def to_dict(self):
        return {'id': self.id, 'name': self.name, 'email': self.email}

# 初始化数据库
@app.before_first_request
def create_tables():
    db.create_all()

# 1. 根据User对象查询数据
@app.route('/user', methods=['GET'])
def get_user():
    user_id = request.args.get('id', type=int)
    if user_id:
        user = User.query.get(user_id)
        if user:
            return jsonify(user.to_dict())
        else:
            return jsonify({'message': 'User not found'}), 404
    else:
        return jsonify({'message': 'Invalid request'}), 400

# 2. 根据User对象修改数据
@app.route('/user', methods=['PUT'])
def update_user():
    user_id = request.json.get('id')
    name = request.json.get('name')
    email = request.json.get('email')
    if user_id and name and email:
        user = User.query.get(user_id)
        if user:
            user.name = name
            user.email = email
            db.session.commit()
            return jsonify({'message': 'User updated successfully'})
        else:
            return jsonify({'message': 'User not found'}), 404
    else:
        return jsonify({'message': 'Invalid request'}), 400

# 3. 根据数组批量删除数据
@app.route('/user', methods=['DELETE'])
def delete_users():
    user_ids = request.json.get('ids')
    if user_ids:
        for user_id in user_ids:
            user = User.query.get(user_id)
            if user:
                db.session.delete(user)
        db.session.commit()
        return jsonify({'message': 'Users deleted successfully'})
    else:
        return jsonify({'message': 'Invalid request'}), 400

# 4. 批量添加数据
@app.route('/user', methods=['POST'])
def add_users():
    users = request.json.get('users')
    if users:
        for user_data in users:
            name = user_data.get('name')
            email = user_data.get('email')
            if name and email:
                user = User(name=name, email=email)
                db.session.add(user)
        db.session.commit()
        return jsonify({'message': 'Users added successfully'})
    else:
        return jsonify({'message': 'Invalid request'}), 400

if __name__ == '__main__':
    app.run(debug=True)